﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using MidimediaFinder.Resources;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using System.IO;

namespace MidimediaFinder
{
    public partial class EditCommentPage : PhoneApplicationPage
    {
        public List<Button> Stars_Buttons;
        public List<Button> DisabledStars_Buttons;
        public static item SelectedItem = null;
        bool working = false;
        private int stars = 0;

        public EditCommentPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (SelectedItem == null)
            {
                NavigationService.GoBack();
            }
            Stars_Buttons = new List<Button>();
            DisabledStars_Buttons = new List<Button>();
            Stars_Buttons.Add(Star1_Button);
            Stars_Buttons.Add(Star2_Button);
            Stars_Buttons.Add(Star3_Button);
            Stars_Buttons.Add(Star4_Button);
            Stars_Buttons.Add(Star5_Button);

            DisabledStars_Buttons.Add(Star1_Button_Disabled);
            DisabledStars_Buttons.Add(Star2_Button_Disabled);
            DisabledStars_Buttons.Add(Star3_Button_Disabled);
            DisabledStars_Buttons.Add(Star4_Button_Disabled);
            DisabledStars_Buttons.Add(Star5_Button_Disabled);
            SetElements();

        }

        private void SetElements()
        {
            if (SelectedItem.MyComment!=null && SelectedItem.MyComment.Username == "")
                SelectedItem.MyComment = null;
            var mycomment = SelectedItem.MyComment;
            if (mycomment != null)
            {
                Username_Area.Text = mycomment.Username;
                Password_Area.Visibility = System.Windows.Visibility.Collapsed;
                PasswordLabel.Visibility = System.Windows.Visibility.Collapsed;
                Comment_Area.Text = mycomment.Comment;
                SetStars(mycomment.Stars);
                Send_Button.Content = Strings.EditComment;

            }
            else
            {
                Send_Button.Content = Strings.SendComment;
                SetStars(0);
                if (SelectedItem.RequestPwd == "1")
                {
                    Password_Area.Visibility = System.Windows.Visibility.Visible;
                    PasswordLabel.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    Password_Area.Visibility = System.Windows.Visibility.Collapsed;
                    PasswordLabel.Visibility = System.Windows.Visibility.Collapsed;
                }
            }


            CharsArea.Text = Comment_Area.Text.Length + " / " + MAX_LENGTH;
        }

        private void Username_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (SelectedItem.RequestPwd == "1")
                {
                    Password_Area.Focus();
                }
                else
                    Comment_Area.Focus();
            }
            
        }
        string old_comment = "";
        int MAX_LENGTH = 140;
        private void Comment_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Send_Button_Click(null, null);
            }

        }
        private void Comment_Area_KeyUp(object sender, KeyEventArgs e)
        {
            if (Comment_Area.Text.Length > MAX_LENGTH)
            {
                Comment_Area.Text = old_comment;
                Comment_Area.SelectionStart = Comment_Area.Text.Length;
            }
            else
                old_comment = Comment_Area.Text;
            CharsArea.Text = Comment_Area.Text.Length + " / " + MAX_LENGTH;
        }

        private void Send_Button_Click(object sender, RoutedEventArgs e)
        {
            if(SelectedItem.AllowComments!="1")
            {
                MessageBox.Show(Strings.commentsnotallowed);
                return;
            }
            if (Username_Area.Text == "")
            {
                MessageBox.Show(Strings.EmptyUsername);
                return;
            }
            else if (SelectedItem.MyComment==null && SelectedItem.RequestPwd == "1" && Password_Area.Text == "")
            {
                MessageBox.Show(Strings.EmptyPassword);
                return;
            }
            else
                SendComment();
        }

        private void SetStars(int s)
        {
            stars = s;
            int i;
            for (i = 0; i < s; i++)
            {
                Stars_Buttons[i].Visibility = System.Windows.Visibility.Visible;
                DisabledStars_Buttons[i].Visibility = System.Windows.Visibility.Collapsed;
            }
            for (int j = i; j < DisabledStars_Buttons.Count; j++)
            {
                Stars_Buttons[j].Visibility = System.Windows.Visibility.Collapsed;
                DisabledStars_Buttons[j].Visibility = System.Windows.Visibility.Visible;
            }
            if (s == 0)
            {
                Star1_Button_Disabled.Margin = new Thickness(10, 0, 0, 0);
            }
            else
            {
                Star1_Button_Disabled.Margin = new Thickness(10, -70, 0, 0);
            }

        }

        private void Star1_Button_Click(object sender, RoutedEventArgs e)
        {
            if (stars == 1)
                SetStars(0);
            else
                SetStars(1);
        }

        private void Star2_Button_Click(object sender, RoutedEventArgs e)
        {
            SetStars(2);
        }

        private void Star3_Button_Click(object sender, RoutedEventArgs e)
        {
            SetStars(3);
        }

        private void Star4_Button_Click(object sender, RoutedEventArgs e)
        {
            SetStars(4);
        }

        private void Star5_Button_Click(object sender, RoutedEventArgs e)
        {
            SetStars(5);
        }

        
        private void Password_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                Comment_Area.Focus();
        }

        private void Cancel_Button_Click(object sender, RoutedEventArgs e)
        {
            ToggleOverlay(false);
        }

        public void ToggleOverlay(bool isOpen)
        {
            working = isOpen;
            if (isOpen)
            {
                Cancel_Button.Visibility = System.Windows.Visibility.Visible;

                EnableProgressBar();
                
                Password_Area.Visibility = System.Windows.Visibility.Collapsed;
                PasswordLabel.Visibility = System.Windows.Visibility.Collapsed;
                
                Username_Area.Visibility = System.Windows.Visibility.Collapsed;
                UsernameLabel.Visibility = System.Windows.Visibility.Collapsed;

                for (int i = 0; i < DisabledStars_Buttons.Count; i++)
                {
                    Stars_Buttons[i].Visibility = System.Windows.Visibility.Collapsed;
                    DisabledStars_Buttons[i].Visibility = System.Windows.Visibility.Collapsed;
                }

                Comment_Area.Visibility = System.Windows.Visibility.Collapsed;
                CommentLabel.Visibility = System.Windows.Visibility.Collapsed;

                Send_Button.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                Cancel_Button.Visibility = System.Windows.Visibility.Collapsed;
                DisableProgressBar();

                SetStars(stars);

                Username_Area.Visibility = System.Windows.Visibility.Visible;
                UsernameLabel.Visibility = System.Windows.Visibility.Visible;

                Comment_Area.Visibility = System.Windows.Visibility.Visible;
                CommentLabel.Visibility = System.Windows.Visibility.Visible;

                if (SelectedItem.MyComment == null && SelectedItem.RequestPwd=="1")
                {
                    Password_Area.Visibility = System.Windows.Visibility.Visible;
                    PasswordLabel.Visibility = System.Windows.Visibility.Visible;

                    Send_Button.Content = Strings.SendComment;
                }
                else if(SelectedItem.MyComment == null)
                    Send_Button.Content = Strings.SendComment;

                Send_Button.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void EnableProgressBar()
        {
            Dispatcher.BeginInvoke(() =>
            {
                ToggleProgressBar.IsEnabled = true;
                ToggleProgressBar.IsIndeterminate = true;
                ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
            });
        }
        private void DisableProgressBar()
        {
            Dispatcher.BeginInvoke(() =>
            {
                ToggleProgressBar.IsEnabled = false;
                ToggleProgressBar.IsIndeterminate = false;
                ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            });
        }
        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (working)
            {
                Cancel_Button_Click(null, null);
                e.Cancel = true;
            }
        }

        private void SendComment()
        {
            var url = "http://midimedia.altervista.org/submit_comment.php?xml=1";
            url += "&username=" + Username_Area.Text;
            url += "&poi=" + SelectedItem.Id;
            url += "&stars=" + stars;
            url += "&comment=" + Comment_Area.Text.Replace("\r", "\n");
            url += "&uid=" + Storage.getID();
            if (SelectedItem.MyComment==null && SelectedItem.RequestPwd == "1")
                url += "&pwd=" + Password_Area.Text;
            else
                url += "&pwd=" + SelectedItem.CommentsPwd;

            ToggleOverlay(true);
            
            Storage.getHTML(url,
                s =>
                {
                    if (!working)
                        return;
                    XmlSerializer serializer = new XmlSerializer(typeof(SubmitCommentResult));
                    var reader = new StringReader(s);
                    SubmitCommentResult result = serializer.Deserialize(reader) as SubmitCommentResult;

                    //Console.WriteLine(result.ToString());
                    if (result.error == "1" && result.message == "missingdata")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.MissingData);
                            ToggleOverlay(false);
                        });
                    }
                    else if (result.error == "1" && result.message == "missingphoneid")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.missingphoneid);
                            ToggleOverlay(false);
                        });
                    }
                    else if (result.error == "1" && result.message == "nopoi")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.nopoi);
                            ToggleOverlay(false);
                        });
                    }
                    else if (result.error == "1" && result.message == "commentsnotallowed")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.commentsnotallowed);
                            ToggleOverlay(false);
                        });
                    }
                    else if (result.error == "1" && result.message == "wrongpwd")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.wrongpwd);
                            ToggleOverlay(false);
                        });
                    }
                    else if (result.error == "1" && result.message == "updatefailed")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.updatefailed);
                            ToggleOverlay(false);
                        });
                    }
                    else if (result.error == "1" && result.message == "missingpwd")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.missingpwd);
                            ToggleOverlay(false);
                        });
                    }
                    else if (result.error == "1" && result.message == "insertfailed")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.missingpwd);
                            ToggleOverlay(false);
                        });
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            if(result.message == "updatecomplete")
                                MessageBox.Show(Strings.updatecomplete);
                            else if (result.message == "insertcomplete")
                                MessageBox.Show(Strings.insertcomplete);
                            Send_Button.Content = Strings.EditComment;

                            comment new_comment = new comment()
                            {
                                Comment = Comment_Area.Text,
                                Datetime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(),
                                Id = "0",
                                POI = SelectedItem.Id,
                                Stars = stars,
                                Username = Username_Area.Text,
                                PhoneId = Storage.getID()
                            };

                            if (SelectedItem.MyComment == null)
                            {
                                SelectedItem.Stars += (new_comment.Stars) / Math.Max(1, (SelectedItem.Comments.Count + 1));
                            }
                            else
                            {
                                int old_stars = 0;
                                for (int i = 0; i < SelectedItem.Comments.Count; i++)
                                {
                                    var c = SelectedItem.Comments[i];
                                    if (c.PhoneId == new_comment.PhoneId)
                                    {
                                        old_stars = c.Stars;
                                        SelectedItem.Comments.RemoveAt(i);
                                        break;
                                    }
                                }
                                SelectedItem.Stars -= old_stars / Math.Max(1, (SelectedItem.Comments.Count));
                                SelectedItem.Stars += (new_comment.Stars) / Math.Max(1, (SelectedItem.Comments.Count));
                            }

                            SelectedItem.Comments.Insert(0, new_comment);
                            SelectedItem.MyComment = new_comment;
                            ToggleOverlay(false);
                        });
                    }

                },
                () =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        ToggleOverlay(false);
                        MessageBox.Show(Strings.ConnectionError);
                    });
                });
        }
    }
}